/* eslint-disable no-use-before-define */
/* eslint-disable consistent-return */

import fetch from 'dva/fetch';
import { message, notification } from 'antd';

const codeMessage = {
    200: '服务器成功返回请求的数据。',
    201: '新建或修改数据成功。',
    202: '一个请求已经进入后台排队（异步任务）。',
    204: '删除数据成功。',
    400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
    401: '用户没有权限（令牌、用户名、密码错误）。',
    403: '用户得到授权，但是访问是被禁止的。',
    404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
    406: '请求的格式不可得。',
    410: '请求的资源被永久删除，且不会再得到的。',
    422: '当创建一个对象时，发生一个验证错误。',
    500: '服务器发生错误，请检查服务器。',
    502: '网关错误。',
    503: '服务不可用，服务器暂时过载或维护。',
    504: '网关超时。'
};
/**
 *
 * @param params
 * @returns {Promise<Promise<any> | never>}
 */
// eslint-disable-next-line consistent-return
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function toBase64(params) {
    if (typeof FileReader === 'undefined') {
        message.warning('当前浏览器不支持FileReader');
    } else {
        try {
            const { file } = params.fileInfo;
            if (!/image\/\w+/.test(file.type)) {
                message.warning('请确保文件为图像类型');
                return false;
            }
            const reader = new FileReader();
            reader.onload = () => {
                insertFile({ ...params, fileUrl: this.result });
            };
            reader.readAsDataURL(file);
        } catch (e) {
            message.error(`图片转Base64出错啦！${e.toString()}`);
        }
    }
}

function insertFile(params) {
    params.fileInfo.success({
        url: params.fileUrl,
        meta: {
            id: 'img',
            title: 'xxx',
            alt: 'img'
            // loop: true, // 指定音视频是否循环播放
            // autoPlay: true, // 指定音视频是否自动播放
            // controls: true, // 指定音视频是否显示控制栏
            // poster: 'http://xxx/xx.png', // 指定视频播放器的封面
        }
    });
}

export async function uploadFile(params, notallow) {
    // putPreSignUrl(params);
    // toBase64(params);
    if (notallow) {
        message.warning('最多只能上传5张图片');
        // eslint-disable-next-line no-use-before-define
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        uploadErrorFn(params);
        return false;
    }
    const {
        fileInfo: { file }
    } = params;
    const obj = {
        sysCode: 'OA',
        richText: '1',
        fileNames: [file.name]
    };

    const uploadUrl = '/api/resource/public/oss/v2/produceputpresignurls';
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    const response = await getPreSignature(uploadUrl, {
        method: 'POST',
        body: obj
    });
    console.info('---->', response);
    if (response.data && response.data.length > 0) {
        const { keyName, preUrl, url } = response.data[0];
        const uploadParams = { preUrl, file };
        // 上传至AWS服务器
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        uploadToServer(uploadParams)
            .then(() => {
                const reader = new FileReader();
                reader.addEventListener('load', () => {
                    const info = params;

                    info.fileUrl = url || reader.result;
                    info.keyName = `ADD:${keyName}`;
                    console.log(info, 'info-------');
                    // eslint-disable-next-line @typescript-eslint/no-use-before-define
                    uploadSuccessFn(info);
                });
                reader.readAsDataURL(file);
            })
            .catch(() => {
                // eslint-disable-next-line @typescript-eslint/no-use-before-define
                uploadErrorFn(params);
                // console.log('e', e);
            });
    }
}

const getPreSignature = (url, option) => {
    const defaultOptions = {
        credentials: 'include'
    };
    const newOptions = { ...defaultOptions, ...option };
    if (newOptions.method === 'POST' || newOptions.method === 'PUT' || newOptions.method === 'DELETE') {
        if (!(newOptions.body instanceof FormData)) {
            newOptions.headers = {
                Accept: 'application/json',
                'Content-Type': 'application/json; charset=utf-8',
                ...newOptions.headers
            };
            newOptions.body = JSON.stringify(newOptions.body);
        } else {
            // newOptions.body is FormData
            newOptions.headers = {
                Accept: 'application/json',
                ...newOptions.headers
            };
        }
    }
    return (
        fetch(url, newOptions)
            // eslint-disable-next-line @typescript-eslint/no-use-before-define
            .then(checkStatus)
            .then(response => {
                // DELETE and 204 do not return data by default
                // using .json will report an error.
                if (newOptions.method === 'DELETE' || response.status === 204) {
                    return response.text();
                }
                return response.json();
            })
    );
};
const checkStatus = response => {
    if (response.status >= 200 && response.status < 300) {
        return response;
    }
    const errortext = codeMessage[response.status] || response.statusText;
    notification.error({
        message: `请求错误 ${response.status}: ${response.url}`,
        description: errortext
    });
    const error = new Error(errortext);
    error.name = response.status;
    error.response = response;
    throw error;
};
// 上传至服务器
const uploadToServer = params => {
    const defaultOptions = {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/octet-stream'
        }
    };
    defaultOptions.body = params.file;
    console.log('defaultOptions', defaultOptions);
    return fetch(params.preUrl, defaultOptions);
};
// 超过限制张数
const uploadErrorFn = params => {
    const { fileInfo } = params;
    fileInfo.error({
        msg: 'unable to upload.'
    });
};
// 插入资源文件到富文本中
const uploadSuccessFn = params => {
    const { fileInfo } = params;
    const { file } = fileInfo;
    console.info('file:', file);
    fileInfo.success({
        url: params.fileUrl,
        keyName: params.keyName,
        meta: {
            id: params.keyName,
            title: file.name,
            alt: fileInfo.id,
            loop: true, // 指定音视频是否循环播放
            // autoPlay: true, // 指定音视频是否自动播放
            controls: true // 指定音视频是否显示控制栏
            // poster: 'http://xxx/xx.png', // 指定视频播放器的封面
        }
    });
};
